package cn.pconline.autoclub.web.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserVoted;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.entity.VoteDetail;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.service.VoteService;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * http://rdtrac.pc.com.cn/autoclub/wiki/appapi/4.0
 * app投票controller
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppVoteController {
	
	@Autowired
	private VoteService voteService;
    @Autowired
    private UserAuth userAuth;
    @Autowired 
    private MemberService memberService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private UserService userService;
    @Autowired
    private DynaIndexService dynaIndexService;
	private static final Logger log = LoggerFactory.getLogger(AppVoteController.class);

    
    /**
     * 用户发布投票
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/createVote.do", method = RequestMethod.POST)
    public void createVote(HttpServletRequest request, HttpServletResponse response) {
    	 WebUtils.setEncoding4App(request, response);
         //获取相关参数
         String callback = AppControllerStatic.paramCallback(request);
         String voteTitle = WebUtils.param(request, "voteTitle", "");
         String voteItems = WebUtils.param(request, "voteItems", "");
         //获取用户信息
         User user = userAuth.getUser(request, response);
         JSONObject json = new JSONObject();
         //判断用户是否登录
         if (user == null || user.getUid() <= 0) {
             AppControllerStatic.printErrorMsg(response, "用户未登录", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
         //参数检查
         if(clubMember == null) {
         	AppControllerStatic.printErrorMsg(response, "你还没加车友会", json, callback, AppControllerStatic.V1_VERSION_LATEST);
         	return;
         }
         
         if(voteTitle.isEmpty()){
        	 AppControllerStatic.printErrorMsg(response, "投票标题不能为空", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         if(voteTitle.length() > Vote.VOTETITLE_MAX_LENGTH){
        	 AppControllerStatic.printErrorMsg(response, "投票标题长度不能超过50", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         String[] voteItemsArray  = voteItems.split(",");
         if(voteItemsArray.length < 2 || voteItemsArray.length > 8) {
        	 AppControllerStatic.printErrorMsg(response, "投票项个数[2-8]", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         //判断是否有重复的投票选项
         HashSet<String> hashSet = new HashSet<String>();
         for(String item : voteItemsArray) {
        	 hashSet.add(item);
         }
         if(hashSet.size() != voteItemsArray.length) {
        	 AppControllerStatic.printErrorMsg(response, "投票项不可以重复", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         List<VoteDetail> voteDetails  = new ArrayList<VoteDetail>();
         for(String voteItem : voteItemsArray){
        	 if(voteItem.length() > VoteDetail.VOTEITEM_MAX_LENGTH) {
        		 AppControllerStatic.printErrorMsg(response, "投票项长度不能超过255", json, callback, AppControllerStatic.V1_VERSION_LATEST);
                 return;
        	 }
        	 if(voteItem != null && !voteItem.isEmpty()){
        		 VoteDetail voteDetail = new VoteDetail();
        		 voteDetail.setContent(voteItem);
        		 voteDetails.add(voteDetail);
        	 }
         }
         
         long clubId = clubMember.getClubId();
         Vote vote = new Vote();
         vote.setClubId(clubId);
         vote.setCreateBy(user.getUid());
         vote.setCreateAt(new Date());
         vote.setUpdateBy(user.getUid());
         vote.setUpdateAt(new Date());
         vote.setVoteTitle(voteTitle);
         vote.setStatus(Vote.STATUS_NORMAL);
         
         boolean result = voteService.createVote(vote,voteDetails);
         
         if(!result){
        	 AppControllerStatic.printErrorMsg(response, "创建投票标题失败", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         //创建投票动态
         AbstractDyna abstractDyna = new AbstractDyna();
         abstractDyna.setClubId(clubId);
         abstractDyna.setContent(voteTitle);
         abstractDyna.setTargetId(vote.getVoteId());
         abstractDyna.setCreateBy(user.getUid());
         abstractDyna.setCreateDate(new Date());
         abstractDyna.setCreateName(user.getUsername());
         dynaService.createVoteDyna(abstractDyna, null);
         
         AppControllerStatic.printSuccessMsg(response, json, callback, AppControllerStatic.V1_VERSION_LATEST);
       
    }
    
    /**
     * 判断用户是否已投票
     * 1.1.3 
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/hasVoted.do", method = RequestMethod.GET)
    public void hasVoted(HttpServletRequest req, HttpServletResponse resp){
    	WebUtils.setEncoding4App(req, resp);
    	JSONObject json = new JSONObject();
    	String callback = AppControllerStatic.paramCallback(req);
    	long userId = AppControllerStatic.paramUserId(req);
    	long voteId = WebUtils.paramLong( req, "voteId", 0);
    	if(userId<=0){
    		AppControllerStatic.printErrorMsg(resp, "非法参数userId！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	}
    	if(voteId<=0){
    		AppControllerStatic.printErrorMsg(resp, "非法参数voteId！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	}
    	UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
    	json.put("userId",userId);
		json.put("voteId",voteId);
    	if(userVote!=null){
    		json.put("hasVoted",Vote.HAS_VOTED);
    		json.put("voteItemId", userVote.getVoteItemId());
    	}else{
    		json.put("hasVoted",Vote.NOT_VOTED);
    		json.put("voteItemId", 0);
    	}

    	AppControllerStatic.printSuccessMsg(resp, json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	
    }
    
    /**
     * 根据投票ID，获取投票详情
     * @param request
     * @param response
     */
    @RequestMapping(value="/1.0/vote/getVoteDetail.do", method=RequestMethod.GET)
    public void getVoteDetail(HttpServletRequest request, HttpServletResponse response) {
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        long voteId = WebUtils.paramLong(request, "voteId", 0);
        
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        
        //判断投票是否存在
        Vote vote = voteService.getValidVote(voteId);
        if(vote == null) {
        	AppControllerStatic.printErrorMsg(response, "投票不存在，或已被删除", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //获取投票选项
        List<VoteDetail> voteDetails = voteService.listDetailsByVoteId(voteId);
        for(VoteDetail voteDetail : voteDetails) {
        	JSONObject json = new JSONObject();
        	json.put("voteItemId", voteDetail.getVoteItemId());
        	String voteItem = voteDetail.getContent();
        	json.put("voteItem", xssEncode == 0 ? voteItem : EncodeUtils.encodeForHTMLFilterNull(voteItem));
        	json.put("voteItemCount", voteDetail.getVoteCount());
        	jsonArray.add(json);
        }
        
        jsonObject.put("voteId", vote.getVoteId());
        String voteTitle = vote.getVoteTitle();
        jsonObject.put("voteTitle", xssEncode == 0 ? voteTitle : EncodeUtils.encodeForHTMLFilterNull(voteTitle));
        jsonObject.put("voteCount", vote.getVoteCount());
        long createrId = vote.getCreateBy();
        jsonObject.put("createBy", createrId);
        jsonObject.put("nickName", userService.getNickNameByUserId(createrId));
        jsonObject.put("clubId", vote.getClubId());
        jsonObject.put("voteItems", jsonArray);
        
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
   
    /**
     * 用户进行投票
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/takeVote.do", method = RequestMethod.POST)
    public void takeVote(HttpServletRequest request, HttpServletResponse response) {
    	 WebUtils.setEncoding4App(request, response);
         //获取相关参数
         String callback = AppControllerStatic.paramCallback(request);
         long voteId = WebUtils.paramLong(request, "voteId", 0);
         long voteItemId = WebUtils.paramLong(request, "voteItemId", 0);
         //获取用户信息
         User user = userAuth.getUser(request, response);
         JSONObject json = new JSONObject();
         //判断用户是否登录
         if (user == null || user.getUid() <= 0) {
             AppControllerStatic.printErrorMsg(response, "用户未登录", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         long userId = user.getUid();

         //是否加入车友会
         ClubMember clubMember = memberService.findClubMemberByUserId(userId);
         if(clubMember == null) {
         	AppControllerStatic.printErrorMsg(response, "你还没加车友会", json, callback, AppControllerStatic.V1_VERSION_LATEST);
         	return;
         }
               
         //投票信息校验
         Vote vote = voteService.getValidVote(voteId);
         VoteDetail voteDetail = voteService.findVoteDetailByVoteItemId(voteItemId);
         if(vote == null){
        	 AppControllerStatic.printErrorMsg(response, "该投票活动不存在", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         if(voteDetail == null){
        	 AppControllerStatic.printErrorMsg(response, "该投票项不存在", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         if(vote.getVoteId() != voteDetail.getVoteId()) {
        	 AppControllerStatic.printErrorMsg(response, "该投票活动不存在此选项", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         //是否本车友会的投票活动
         if(clubMember.getClubId() != vote.getClubId()) {
        	 AppControllerStatic.printErrorMsg(response, "只能参加本车友会的投票活动", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         //用户是否已经成功投票过
         UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
         if(userVote != null) {
        	 AppControllerStatic.printErrorMsg(response, "你已经成功投票过，不能重复投票", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
         
         long result = voteService.createUserVoted(vote, voteDetail, userId);
         
         if(result != 0){
        	 AppControllerStatic.printErrorMsg(response, "用户投票失败", json, callback, AppControllerStatic.V1_VERSION_LATEST);
             return;
         }
              
         AppControllerStatic.printSuccessMsg(response, json, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.3.6 删除投票
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/deleteVote.do", method = RequestMethod.POST)
    public void deleteVote(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding4App(request, response);
    	 //获取相关参数
        String callback = AppControllerStatic.paramCallback(request);
        long voteId = WebUtils.paramLong(request, "voteId", 0);
        //获取用户信息
        User user = userAuth.getUser(request, response);
        JSONObject jsonObject = new JSONObject();
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //判断投票是否存在
        Vote vote = voteService.getValidVote(voteId);
        if(vote == null) {
        	AppControllerStatic.printErrorMsg(response, "该投票活动不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //判断登录用户是否有删除操作权限--管理员(副会长、会长)，或者投票发布者
        boolean hasDeleteRole = false;
        long userId = user.getUid();
        if(userId == vote.getCreateBy()){ // 投票创建者
        	hasDeleteRole = true;
        }else{
        	long clubId = vote.getClubId();
        	hasDeleteRole = memberService.isClubNormalAdmin(userId, clubId);
        }
        if(!hasDeleteRole) {
        	AppControllerStatic.printErrorMsg(response, "没有删除权限", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        } 
        //删除投票
        int deleteResult = voteService.deleteVote(voteId);
        //删除车友会投票动态
        if(deleteResult > 0) {
        	DynaInfo dynaInfo = dynaService.findDynaByTypeTargetId(DynaInfo.TYPE_VOTE, voteId, vote.getCreateAt());
        	if(dynaInfo != null) {
        		dynaService.deleteClubDyna(vote.getClubId(), dynaInfo.getDynaInfoId());//删除车友会投票动态
        		dynaService.deleteUserDyna(dynaInfo.getCreateBy(), dynaInfo.getDynaInfoId());//删除个人投票动态
        		dynaIndexService.deleteDynaIndex(dynaInfo.getDynaInfoId());	//删除动态索引
        	}
        }
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
}
